import requests
import time
import os
import multiprocessing as mp


#yearlist = [2005, 2006, 2007, 2008, 2009, 2010]
#lastlist = [160921, 166189, 172469, 170632, 163523, 170101]


def downloader(ind):
    digit = len(str(ind))
    string = "0"*(7-digit)+str(ind)      #### Application Number ####
    appnumber = "10"+ str(year) + string
    url = "http://plus.kipris.or.kr/kipo-api/kipi/patUtiModInfoSearchSevice/getBibliographyDetailInfoSearch?applicationNumber=10"+ str(year) +string+"&ServiceKey=vHYkrSLI1J9sKpwQ/7gcIO7IGdVenwwsR7iKOigsXlQ="
    start = time.time()
    while True:
        try:
        	response = requests.get(url)
        	break
        except:
            time.sleep(1)
            pass
    end = time.time()
    A = end - start
    if A < 1:
        time.sleep(1 - A)
    data = response.content
    with open('D:\\KIPRIS\\Biblio\\'+str(year) + '\\'+ str(appnumber)+'.xml', 'wb') as f:
        f.write(data)
    n = os.path.getsize('D:\\KIPRIS\\Biblio\\'+str(year) + '\\'+ str(appnumber)+'.xml')
    size = round(n / 1024.0, 1)
    A = round(A, 3)
    print(str(appnumber)+ ' - ' + str(response.status_code)+ ' - ' +str(A) +'sec - ' +str(size) + 'KB')

#yearstr = input("year = ")
#laststr = input("How many applications in the year? = ")
lastlist = [169, 233, 126, 30, 91, 76, 132, 156, 287, 469, 555, 703, 611, 858, 782, 771, 908, 1018, 1060, 1177, 1463, 1701, 1846, 1906, 1995, 2398, 4455, 2914, 3261, 3139, 4015, 4722, 5070, 5303, 5924, 6394, 8633, 10587, 12759, 17062, 20051, 23315, 25820, 28132, 31073, 36491, 45712, 78499, 90326, 92734, 75999, 80642, 102010, 104612, 106100, 118652, 140000, 159999, 164999, 162553, 169999, 148019, 170100, 179999, 185416, 204999, 209999, 214999, 209999, 214999, 149999]
# 1948~2018
year = 1996
last = lastlist[year-1948]
indlist = range(1, last+1)
consume = time.time()
if __name__ == '__main__':
    pool = mp.Pool(30)
    pool.map(downloader, indlist)
    pool.close()
print(time.time() - consume)